package com.service;

import com.bean.Express;
import com.dao.BaseExpressDao;
import com.dao.impl.ExpressDapMysql;
import com.exception.DuplicateCodeException;
import com.util.RandomUtil;

import java.util.List;
import java.util.Map;

public class ExpressService {
    BaseExpressDao baseExpressDao = new ExpressDapMysql();

    public List<Map<String, Integer>> console() {
        return baseExpressDao.console();
    }


    public List<Express> findAll(boolean limit, int offset, int pageNumber) {
        return baseExpressDao.findAll(limit, offset, pageNumber);
    }


    public Express findByNumber(String number) {
        return baseExpressDao.findByNumber(number);
    }


    public Express findByCode(String code) {
        return baseExpressDao.findByCode(code);
    }


    public List<Express> findByUserPhone(String userPhone) {
        return baseExpressDao.findByUserPhone(userPhone);
    }


    public List<Express> findBySysPhone(String sysPhone) {
        return baseExpressDao.findBySysPhone(sysPhone);
    }


    public boolean insert(Express e) {
        e.setCode(RandomUtil.getCode() + "");
        try {
            boolean flag = baseExpressDao.insert(e);
            if (flag) {
                //SMSUtil.send(e.getUserPhone(), e.getCode());
            }
            return flag;
        } catch (DuplicateCodeException duplicateCodeException) {
            return insert(e);
        }
    }


    public boolean update(int id, Express e) {
        if (e.getUserPhone() != null) {
            baseExpressDao.delete(id);
            return insert(e);
        } else {
            boolean update = baseExpressDao.update(id, e);
            Express express = baseExpressDao.findByNumber(e.getNumber());
            if (e.getStatus() == 1) {
                updateStatus(express.getCode());
            }
            return update;
        }
    }


    public boolean updateStatus(String number) {
        return baseExpressDao.updateStatus(number);
    }


    public boolean delete(int id) {
        return baseExpressDao.delete(id);
    }

    public List<Express> findByUserPhoneAndStatus(String userPhone, int status) {
        return baseExpressDao.findByUserPhoneAndStatus(userPhone, status);
    }
}
